package cn.bugstack.domain.strategy.service.rule.chain.impl;

import cn.bugstack.domain.strategy.model.entity.RuleActionEntity;
import cn.bugstack.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.bugstack.domain.strategy.repository.IStrategyRepository;
import cn.bugstack.domain.strategy.service.armory.IStrategyDispatch;
import cn.bugstack.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.bugstack.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import cn.bugstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: Zchy
 * @Description: 抽奖前权重过滤链
 * @DateTime: 10/29/2024 5:17 PM
 **/
@Slf4j
@Component("rule_weight")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Override
    public DefaultLogicChainFactory.StrategyAwardVo logic(Long strategyId, String userId) {
        log.info("抽奖责任链-权重过滤 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        //查询规则配置
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        Map<Long, String> ruleWeightMap = getAwardWeightMap(ruleValue);
        if(null == ruleWeightMap || ruleWeightMap.isEmpty()){
            return next().logic(strategyId, userId);
        }
        List<Long> sortedKeys = new ArrayList<>(ruleWeightMap.keySet());
        Collections.sort(sortedKeys);

        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);

        Long nextValue = sortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);

        if (null != nextValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, nextValue);
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultLogicChainFactory.StrategyAwardVo.builder()
                    .awardId(awardId)
                    .ruleModel(ruleModel())
                    .build();
        }

        return next().logic(strategyId, userId);
    }

    private Map<Long, String> getAwardWeightMap(String ruleValue) {
        String[] splitRuleValue = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleWeightMap = new HashMap<>();
        for(String ruleWeight : splitRuleValue){
            if(ruleWeight == null || ruleWeight.isEmpty()){
                return ruleWeightMap;
            }
            String[] split = ruleWeight.split(Constants.COLON);
            if (split.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleWeight);
            }
            ruleWeightMap.put(Long.parseLong(split[0]), split[1]);
        }
        return ruleWeightMap;
    }

    @Override
    protected String ruleModel() {
        return "rule_weight";
    }
}
